// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import requestA from './api/request'
import request from './api/service'
import md5 from 'js-md5'
import { rotersConfig } from "@/config/router.config.js";
import childView from "./views/home/childView.vue";
import {configApi} from "@/config/requestBtnApi.js"
import VueCron from 'vue-cron'
import axios from 'axios'
import VueAxios from 'vue-axios'
import GLOBAL from "./components/global.vue"
import moment from "moment"
import cal from './api/calculation.js'
import BabelPolyfill from "babel-polyfill"
/* 引入echarts */
import echarts from 'echarts'
import { replaceStar, hidInfo } from '@/api/utils.js'
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
Vue.prototype.replaceStar = replaceStar

// tansun组件库
import 'tsvue/lib/tstheme/index.css'
import 'tsvue/lib/tstheme/common/iconfont/iconfont.css'
import tsVue from 'tsvue'
Vue.use(tsVue)

// 工作流部分api
import api from '@/api/flow'
Vue.prototype.$api = api

Vue.prototype.hidInfo = hidInfo
Vue.use(VueAxios, axios)
Vue.prototype.$requestBtnApi = configApi
Vue.prototype.$md5 = md5
Vue.prototype.$requestA = requestA
Vue.prototype.$request = request
Vue.prototype.GLOBAL = GLOBAL
Vue.config.productionTip = false
Vue.use(VueCron)
Vue.use(ElementUI);
Vue.use(BabelPolyfill)
Vue.prototype.$moment = moment
Vue.prototype.cal = cal
function getMenu() {
  const data = {
    tenantCode:localStorage.getItem("TENANT_CODE"),
    userCode: localStorage.getItem("USER_CODE")
  };
  return new Promise(resolve => {
    requestA.get("/IAM/user/permission", data, res => {
      const routerList = buildDynamicMenuRouter(res.data.menuPerm)
      rotersConfig[0].children = []
      for (const key in routerList) {
          rotersConfig[0].children.push(routerList[key])
      }
      sessionStorage.setItem('routerConfig',JSON.stringify(rotersConfig))
      resolve()
    });
  })
};
function buildDynamicMenuRouter(menuList) {
  menuList = menuList || [];
  return menuList.map(item=>{
    let menuRouter = {};
    if(item.eleType == "menu"){
        menuRouter.path=item.menuUrl,
        menuRouter.name=item.permName,
        menuRouter.meta={
          title: item.permName,
          keepAlive: false,
          // isDynamicPage: item.isDynamicPage,
          // dynamicPageType: item.dynamicPageType,
          // pagePk: item.pagePk,
          menuList: []
        };
      if(item.menuId === "0"){
        menuRouter.component = childView
      } else {
        let component = item.menuUrl;
        if (component.indexOf("/") === 0) {
          component = component.substring(1, component.length);
        }
        menuRouter.component = resolve =>
        require([`@/views/${component}`], resolve);
      }
      if(item.children != null){
        if(item.children && item.eleType == 'menu'){
          if(item.children[0].eleType == 'menu'){
            menuRouter.component = childView
          }
          menuRouter.children = buildDynamicMenuRouter(item.children);
        }
      }else{
        menuRouter.children = [];
      }

    }
    if(item.children != null){
      if(item.children && item.children[0].eleType == 'btn'){
        menuRouter.children = []
        item.children.map(item2 => {
              menuRouter.meta.menuList.push({
                eleType: item2.eleType,
                operType: item2.operType,
                permName: item2.permName,
                eleName: item2.eleName,
                eleUrl: "/IAM"+item2.apiUrl
              });
        });
      }
    }
    if(JSON.stringify(menuRouter) != "{}"){
      return menuRouter
    }
  })
}
router.beforeEach((to,from,next)=>{
  // if(localStorage.getItem('Access-Token')){
  //   next()
  // }else{
  //   if(to.path === '/login'){
  //     next()
  //   }else{
  //     next({
  //       path:'/login'
  //     })
  //   }
  // }
  if(!localStorage.getItem('Access-Token')){
    next()
    return false
  }
  if(from.name == null){
    getMenu().then(()=>{
      router.addRoutes(rotersConfig)
      let pathName = sessionStorage.getItem('pathName')
      if(pathName == to.path){
        sessionStorage.removeItem('pathName')
        next()
      }else{
        if(localStorage.getItem('Access-Token')){
          sessionStorage.setItem('pathName', to.path)
          next({...to})
        }else{
          if(to.path === '/login'){
            next({...to})
          }else{
            sessionStorage.setItem('pathName', to.path)
            next({...to})
          }
        }
      }
    })
  }else{
    getMenu().then(()=>{
      router.addRoutes(rotersConfig)
    })
    next()
  }
})
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
